﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Configuration;
using System.Reflection;


namespace Directory.Web
{
	public sealed class RolePanel:Panel
	{
		private string _allowRoles;
		private string _denyText;

		public string AllowRoles
		{
			get { return _allowRoles; }
			set { _allowRoles = value; }
		}
		public string DenyText
		{
			get { return _denyText; }
			set { _denyText = value; }
		}

		protected override void OnLoad(EventArgs e)
		{
			if (ValidateUser())
			{
				base.OnLoad(e);
			}
			else
			{
				this.Controls.Clear();
				if (string.IsNullOrEmpty(DenyText))
				{
					this.Visible = false;
				}
				else
				{
					Literal lt = new Literal();
					lt.Text = DenyText;
					this.Controls.Add(lt);
				}
			}
		}

		protected override void Render(HtmlTextWriter writer)
		{
			//base.Render(writer);
			base.RenderContents(writer);
		}

		public bool ValidateUser()
		{
			if (!Page.User.Identity.IsAuthenticated)
			{
				return false;
			}
			if (AllowRoles == null)
			{
				return false;
			}
			string[] roles = AllowRoles.Split(new char[] { ',' });
			foreach (string role in roles)
			{

				if (WebUtil.IsCurrentUserInRole(role))
				{
					return true;
				}
			}
			return false;
		}
	}
}